package com.swk.login.autologin;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.swk.login.UserBean;

/**
 * 自动登录过滤器
 */
@WebFilter(dispatcherTypes = {
				DispatcherType.REQUEST, 
				DispatcherType.FORWARD, 
				DispatcherType.INCLUDE
		}
					, urlPatterns = { "/index.jsp" })
public class AutoLoginFilter implements Filter {

    public AutoLoginFilter() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

	/**
	 * 自动登录
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		//取得浏览器的Cookie
		Cookie[] cookies = request.getCookies();
		Cookie userCookie = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if("userinfo".equals(cookie.getName())){
					userCookie = cookie;
					break;
				}
			}
			//if found
			if(userCookie != null){
				//取出cookie信息
				String userinfo = URLDecoder.decode(userCookie.getValue(), "UTF-8");
				String[] infos = userinfo.split("_");
				//用户信息存入session
				request.getSession(true).setAttribute("userBean", new UserBean(infos[0], infos[1]));
			}
		}
		
		chain.doFilter(request, response);
	}

	public void destroy() {
	}

}
